package com.blb.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class PreFilter extends ZuulFilter {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }



   @Override
    public Object run() throws ZuulException {
       /* Object accessToken = redisTemplate.opsForValue().get("accessToken");*/
       List<Object> accessToken = redisTemplate.opsForList().range("accessToken", 0, -1);

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //登录成功后需要请求的地址
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);

        if("/note-web/login/pc_loginPage".equals(requestURI)||"/note-notes/notes/getNotes".equals(requestURI)||"/note-user/user/getShareUser".equals(requestURI)||"/note-user/certificate/update".equals(requestURI)|| "/note-user/certificate/login".equals(requestURI)|| "/note-user/certificate/register".equals(requestURI)||"/note-user/certificate/getCode".equals(requestURI)|| "/note-user/certificate/getCode1".equals(requestURI)|| "/note-user/certificate/login1".equals(requestURI)|| "/note-user/certificate/mp_login".equals(requestURI) ){
            System.out.println("123");
            return null;
        }

        String token = request.getParameter("token");
        System.out.println("token:"+token);
        System.out.println("pre过滤器");

        if(token==null || accessToken.isEmpty()){
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(200);
            currentContext.setResponseBody("请先登录");
        }else{
            if(accessToken.contains(token)){
                currentContext.setSendZuulResponse(true);
            }else{
                currentContext.setSendZuulResponse(false);
                currentContext.setResponseStatusCode(200);
                currentContext.setResponseBody("请先登录");
            }
        }
        return null;
    }
}
